<template>
  <div class="reportwork">
    <div class="addWork" v-if="!showAdd">
      <div class="toolBar">
        <!-- <el-input
        v-model="searchWord"
        size="small"
        @clear="getWorkList"
        style="width: 30%"
        type="text"
        placeholder="项目名称"
        clearable
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
        <el-button
          @click="getWorkList"
          slot="append"
          icon="el-icon-search"
        ></el-button>
      </el-input> -->
        <el-select v-model="status" @change="getWorkList" size="small">
          <el-option
            v-for="(item, index) in statusNow"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button
          @click="addworktime"
          style="margin-left: 10px"
          size="small"
          type="primary"
          ><i class="el-icon-plus"></i> 填报工时</el-button
        >
        <el-button
          @click="showSetting = true"
          style="margin-left: 10px"
          size="small"
          type="primary"
          ><i class="el-icon-setting"></i> 报工设置</el-button
        >
        <el-button
          @click="deleteKind"
          size="small"
          type="danger"
          v-if="status == false"
          ><i class="el-icon-delete"></i> 删除选中</el-button
        >
      </div>
      <div class="content">
        <el-table
          border
          stripe
          size="small"
          :highlight-current-row="true"
          :data="tableData"
          style="width: 100%"
          height="490"
          @selection-change="selectDelete"
          :row-class-name="showStatus"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="groupTypeName" label="所属群组"></el-table-column>
          <el-table-column
            prop="workKindName"
            label="工作分类"
            show-overflow-tooltip=""
          ></el-table-column>
          <el-table-column
            prop="projectName"
            label="项目名称"
            show-overflow-tooltip=""
          ></el-table-column>
          <el-table-column
            prop="projectType"
            label="项目类型"
          ></el-table-column>
          <el-table-column prop="workTime" label="填报工时"></el-table-column>
          <el-table-column prop="evaluate" label="评价" show-overflow-tooltip=""></el-table-column>
          <el-table-column prop="startLevel" label="评分"></el-table-column>
          <!-- <el-table-column
            prop="workStartTime"
            label="工作起始时间"
            show-overflow-tooltip=""
          ></el-table-column> -->
          <!-- <el-table-column
            prop="workEndTime"
            label="工作结束时间"
            show-overflow-tooltip=""
          ></el-table-column> -->
          
          <el-table-column
            prop="workDescribe"
            label="工作描述"
            show-overflow-tooltip=""
          ></el-table-column>
          <el-table-column prop="makeUsername" label="确认人"></el-table-column>
          <el-table-column prop="makeStatus" label="处理状态">
            <template slot-scope="scope">
              <span>{{
                scope.row.makeStatus != null
                  ? scope.row.makeStatus
                    ? "已确认"
                    : "未通过"
                  : "未确认"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="填报时间"
            show-overflow-tooltip=""
          ></el-table-column>
          <el-table-column
            align="center"
            label="操作"
            :width="doitWidth"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button @click="edit(scope.row)" size="mini" type="primary" :disabled="status!=false">
                <i class="el-icon-edit"></i>
              </el-button>
              <el-button
                @click="removeKind(scope.row.id)"
                size="mini"
                type="danger"
                v-if="status == false"
                ><i class="el-icon-delete"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            small
            background
            layout="total, prev, pager, next"
            :total="total"
            @current-change="goSize"
          >
          </el-pagination>
        </div>
      </div>
      <el-dialog title="报工设置" :visible.sync="showSetting">
        <el-form size="small">
          <el-form-item label="每日工时">
            <el-input
              v-model="set.dayWorkTime"
              type="number"
              placeholder="每日工时"
            ></el-input>
          </el-form-item>
          <el-form-item label="填报周期">
            <el-input
              v-model="set.cycleWorkTime"
              type="number"
              placeholder="填报周期（单位：天）"
            ></el-input>
          </el-form-item>
          <el-form-item class="diaBtn">
            <el-button type="primary" @click="setWork">确定</el-button>
            <el-button @click="showSetting = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <div class="reportworkedit" v-if="showAdd">
      <div class="editItem">
        <span>确认人</span>
        <el-select
          v-model="add.makeUserId"
          style="margin-left: 34px; width: 175px"
        >
          <el-option
            v-for="(item, index) in powerList"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <div class="editItem">
        <span>工作分类</span>
        <el-select
          v-model="add.workKindId"
          style="margin-left: 20px; margin-right: 100px; width: 175px"
        >
          <el-option
            v-for="(item, index) in workKindList"
            :key="index"
            :label="item.workName"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <div class="editItem">
        <span>所属项目</span>
        <el-select
          placeholder="选择分类"
          v-model="projectTypeId"
          @change="getNewProjectList"
          filterable
          clearable
          style="margin-left: 20px; width: 175px"
        >
          <el-option
            v-for="(item, index) in projectTypeList"
            :key="index"
            :label="item.typeName"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-select
          placeholder="选择项目"
          v-model="add.projectId"
          @change="getTaskByProject"
          filterable
          clearable
          style="margin: 0 20px; width: 425px"
        >
          <el-option
            v-for="(item, index) in newProjectList"
            :key="index"
            :label="item.projectName"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-select
          placeholder="任务（选填）"
          v-model="add.taskId"
          filterable
          clearable
          style="margin: 0; width: 175px"
        >
          <el-option
            v-for="(item, index) in taskList"
            :key="index"
            :label="item.taskName"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <div class="editItem">
        <span>所属组群</span>
      <div
      style="margin-top: -20px; margin-left: 38.75px">
          <el-radio-group v-model="groupType" @change="getGroupTree" style="padding-top: 10px;">
            <el-radio label="bu">BU</el-radio>
            <el-radio label="dept">部门</el-radio>
          </el-radio-group>
          <el-cascader
            v-model="groupIds"
            clearable
            :options="options"
            :props="{ expandTrigger: 'hover', value: 'id', label: 'kindName' }"
            @change="handleChange"
            style="margin-left: 10px"
          >
          </el-cascader>
      </div>
      </div>
      <div class="editItem">
        <span>起止日期</span>
        <div
          style="position: relative; margin-top: -30px; margin-left: 38.75px"
        >
          <el-date-picker
            @change="selectDate2"
            v-model="add.workStartTime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="起始日期"
            style="width: 175px"
          >
          </el-date-picker
          ><span style="margin: 0 10px">至</span
          ><el-date-picker
            @change="selectDate"
            v-model="add.workEndTime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="截至日期"
            style="width: 175px; margin-left: 0px"
          >
          </el-date-picker>
          <el-select
          placeholder="快捷（选填）"
          v-model="quickdate"
          clearable
          @change="quickDate"
          style="margin: 0 20px; width: 175px"
        >
          <el-option
            v-for="(item, index) in quickdateList"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
          <span
            v-if="showCycleWaring"
            style="color: red; margin-left: 20px; font-size: 12px"
          >
            超出设定周期</span
          >
        </div>
      </div>
      <div class="editItem">
        <span>工时统计</span>
        <el-input
          style="width: 100px; margin-left: 20px"
          v-model="add.workTime"
          type="number"
        ></el-input>
        <span
          v-if="subTime*8 < add.workTime"
          style="color: red; margin-left: 20px; font-size: 12px"
        >
          根据报工设置已超出预定工时</span
        >
      </div>
      <div class="editItem">
        <span>项目描述</span>
        <div>
          <el-input
            v-model="add.workDescribe"
            type="textarea"
            placeholder="项目描述"
            style="width: 95%; margin-left: 38.75px"
          ></el-input>
        </div>
      </div>
      <!-- <div class="editItem">
              <span>评价</span>
              <div><el-rate
              style="margin-left:0px;"
              v-model="score"
              show-score
              allow-half
              text-color="#C6D1DE"
              score-template="{value}">
            </el-rate>
            <textarea rows="2" style="margin-top:10px;padding:15px;width:100%;"></textarea></div>  
          </div> -->
      <div class="editButton">
        <el-button
          @click="addTask"
          style="
            height: 32.5px;
            line-height: 7.5px;
            width: 80px;
            color: #ffffff;
            background: #3c9df7;
          "
          >确 定</el-button
        ><el-button
          @click="showAdd = false"
          style="
            height: 32.5px;
            line-height: 7.5px;
            width: 80px;
            color: #000000;
            background: #eeeeee;
            margin-left: 200px;
          "
          >返 回</el-button
        >
      </div>
    </div>
  </div>
</template>
<script>
import * as api from "@/js/workTimeApi";
// import * as userApi from "@/js/userApi";
export default {
  name: "AddProject",
  data() {
    return {
      searchWord: null,
      tableData: [],
      total: 0,
      deleteIdList: [],
      showAdd: false,
      showAddProjectKind: false,
      add: {
        projectTypeId: 1,
      },
      projectTypeList: [],
      groupType:'',
      isEditBtn: false,
      projectList: [],
      newProjectList: [],
      newProjectKind: null,
      pageNum: 1,
      pageSize: 10,
      projectTypeId: null,
      workKindList: [],
      powerList: [],
      taskList: [],
      set: {},
      options: [],
      groupIds: [],
      showSetting: false,
      workTimeLimit: 0,
      workCycleLimit: 0,
      showCycleWaring: false,
      groupPowerList: [],
      subTime:0,
      status: null,
      statusNow: [
        {
          label: "未确认",
          value: null,
        },
        {
          label: "已确认",
          value: true,
        },
        {
          label: "未通过",
          value: false,
        },
      ],
      console: "",
      quickdate:'',
      quickdateList: [
        {
          label: "当天",
          value: 1,
        },
        {
          label: "当周",
          value: 5,
        }
      ]
    };
  },
  methods: {
    quickDate(val){
      let today=this.GetDateStr(0)
      let week=new Date().getDay()
      let weektoday=this.GetDateStr(1-week)
      let weeklast=this.GetDateStr(5-week)
      if(val==1){
        this.$set(this.add, "workStartTime", new Date())
        this.$set(this.add, "workEndTime", new Date())
        this.add.workStartTime=today
        this.add.workEndTime=today
        this.subTime=1
      }
      else if(val==5){
        this.$set(this.add, "workStartTime", new Date())
        this.$set(this.add, "workEndTime", new Date())
        this.add.workStartTime=weektoday
        this.add.workEndTime=weeklast
        this.subTime=5
      }
      else{
        this.add.workStartTime=null
        this.add.workEndTime=null
        this.showCycleWaring=false
      }
    },
    GetDateStr(AddDayCount) {
      var dd = new Date();
      dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
      var y = dd.getFullYear();
      var m = dd.getMonth()+1;//获取当前月份的日期
      var d = dd.getDate();
      return y+"-"+m+"-"+d;
    },
    //获取群组树形结构
    getGroupTree() {
      api.getGroupKindTree({ kindCode: this.groupType }).then((res) => {
        this.options = res.data;
      });
    },
    selectDate2(){
      this.quickdate=''
    },
    //选择日期
    selectDate() {
      this.quickdate=''
      let endTimeDate = new Date(
        Date.parse(this.add.workEndTime.replace(/-/g, "/"))
      );
      let startTimeDate = new Date(
        Date.parse(this.add.workStartTime.replace(/-/g, "/"))
      );
      let subTime = (endTimeDate - startTimeDate) / 1000 / 60 / 60 / 24; //计算俩个日期相差几天
      this.subTime=subTime+1
      if (subTime < 0) {
        this.$message({
          type: "error",
          message: "截止日期需大于起始日期",
        });
        this.add.workEndTime = null;
        this.add.workStartTime = null;
      }
      if (subTime > this.workCycleLimit) {
        // console.log('大于周期')
        this.showCycleWaring = true;
        return;
      }
      this.showCycleWaring = false;
      // console.log(subTime,this.workCycleLimit)
    },
    //填报工时
    addworktime() {
      this.showAdd = true;
      this.add = {
        projectTypeId: 1,
      };
      this.projectTypeId=null
    },
    //报工设置
    setWork() {
      this.set.userId = sessionStorage.getItem("userId");
      // console.log(this.set)
      api.createWorkSet(this.set).then((res) => {
        if (res.status == "success") {
          this.$message({
            type: "success",
            message: "设置成功",
          });
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
        this.showSetting = false;
      });
    },
    //根据项目获取任务
    getTaskByProject(id) {
      if(this.add.taskId!=null){
        this.add.taskId=null
      }
      api
        .getWorkTaskList({ projectId: id, pageNum: 1, pageSize: 100 })
        .then((res) => {
          this.taskList = res.data.records;
        });
    },
    getNewProjectList(val){
      this.newProjectList=[]
      this.add.projectId=null
      this.projectList.forEach(element => {
        if(element.projectTypeId==val){
          this.newProjectList.push(element)
        }
      })
    },
    //展示行状态
    showStatus(row) {
      if (row.makeStatus != null && row.makeStatus) {
        return "success-row";
      }
      if (row.makeStatus != null && row.makeStatus) {
        return "warning-row";
      }
      return "";
    },
    //跳页
    goSize(currentPage) {
      this.pageNum = currentPage;
      this.getProjectList();
    },
    //查询
    getWorkList() {
      let param = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        userId: sessionStorage.getItem("userId"),
        makeStatus: this.status,
      };
      api.getWorkList(param).then((res) => {
        // console.log(res);
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
      api.getNormalUserMessage();
      api.getPowerUserMessage();
    },
    //查询项目列表
    getProjectList() {
      api.getProjectList().then((res) => {
        if (res.status === "success") {
          this.projectList = res.data.rows;
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
      });
    },
    //选择删除
    selectDelete(data) {
      let temp = [];
      data.forEach((element) => {
        temp.push(element.id);
      });
      // console.log(temp);
      this.deleteIdList = temp;
    },
    removeKind(id) {
      this.deleteIdList = [];
      this.deleteIdList.push(id);
      this.deleteKind();
    },
    //删除
    deleteKind() {
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.deleteWorkTask(this.deleteIdList).then((res) => {
            if (res.status == "success") {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getWorkList();
              this.deleteIdList = [];
            } else {
              this.$message({
                type: "error",
                message: res.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //新增项目
    addTask() {
      let createUsername = JSON.parse(sessionStorage.getItem("userInfo")).name;
      let createUserId = sessionStorage.getItem("userId");
      this.add.username = createUsername;
      this.add.userId = createUserId;
      if (
        this.add.makeUserId == null ||
        this.add.workKindId == null ||
        this.add.projectId == null ||
        this.add.workStartTime == null ||
        this.add.workEndTime == null ||
        this.add.workTime == null ||
        this.add.workDescribe == null
      ) {
        this.$message({
          type: "warning",
          message: "请填写除选填内容后操作",
        });
        return;
      }
      let makeUsername = this.powerList.find((value) => {
        return value.id == this.add.makeUserId;
      }).name;
      this.add.makeUsername = makeUsername;
      if (this.isEditBtn) {
        this.add.makeStatus = null;
        api.updateWork(this.add).then((res) => {
          if (res.status == "success") {
            this.$message({
              type: "success",
              message: "修改成功",
            });
          } else {
            this.$message({
              type: "error",
              message: res.message,
            });
          }
          this.getWorkList();
          this.isEditBtn = false;
          this.showAdd = false;
        });
      } else {
        api.addWrok(this.add).then((res) => {
          if (res.status == "success") {
            this.$message({
              type: "success",
              message: "添加成功",
            });
            this.getWorkList();
          } else {
            this.$message({
              type: "error",
              message: res.message,
            });
          }
          this.showAdd = false;
        });
      }
    },
    //编辑
    edit(data) {
      this.add = data;
      api.getPowerUserByGroup(data.id).then((res) => {
        // console.log("筛选用户", res);
        this.console = res;
      });
      this.showAdd = true;
      this.isEditBtn = true;
    },
    //获取项目类型列表
    getProjectTypeList() {
      api.getProjectTypeList().then((res) => {
        this.projectTypeList = res.data.rows;
      });
    },
    //获取工作分类列表
    getWorkKindList() {
      api.getWorkKindList().then((res) => {
        this.workKindList = res.data.rows;
      });
    },
    //级联选项
    handleChange(data) {
      this.add.groupTypeId = data[data.length - 1];
      // console.log(data[data.length - 1]);
    },
    //新增项目分类
    addProjectKind() {
      api.createProjectKind({ typeName: this.newProjectKind }).then((res) => {
        if (res.status == "success") {
          this.$message({
            type: "success",
            message: "添加成功",
          });
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
        this.showAddProjectKind = false;
        this.getProjectTypeList();
      });
    },
    //获取用户列表
    getUserList() {
      api.getUserList().then((res) => {
        // console.log(res);
        this.console = res;
      });
    },
    //获取有审批权限的人
    async getPowerUserList() {
      await this.getGroupPowerList();
      api.getHavePowerUserList().then((res) => {
        // console.log(res);
        this.powerList = [];
        // console.log("dddddd=>", this.groupPowerList);
        this.groupPowerList.forEach((element) => {
          let obj = res.data.find((value) => {
            return element == value.id;
          });
          this.powerList.push(obj);
        });
        // console.log("本组有权限的", this.powerList);
      });
    },
    async getGroupPowerList() {
      api
        .getGroupPowerByUserId({ userId: sessionStorage.getItem("userId") })
        .then((res) => {
          this.groupPowerList = res.data;
        });
    },
    //根据用户ID获取用户的报工设置
    getWorkSetByUserId() {
      api
        .getWorkSetting({ userId: sessionStorage.getItem("userId") })
        .then((res) => {
          if (res.data.records.length == 0) {
            this.$confirm("检测到您未设置报工信息, 是否设置?", "提示", {
              confirmButtonText: "设置",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.showSetting = true;
              })
              .catch(() => {});
          } else {
            // console.log("ddd->", res.data.records);
            this.set.dayWorkTime = res.data.records[0].dayWorkTime;
            this.set.cycleWorkTime = res.data.records[0].cycleWorkTime;
            this.workTimeLimit =
              res.data.records[0].dayWorkTime *
              res.data.records[0].cycleWorkTime;
            this.workCycleLimit = res.data.records[0].cycleWorkTime;
            // console.log("ddd->", this.workTimeLimit);
          }
        });
    },
  },
  computed: {
    doitWidth() {
      if (this.status == false) {
        return 180;
      } else {
        return 90;
      }
    },
  },
  async mounted() {
    // console.log("子页面session：" + sessionStorage.getItem("username"));
    this.getWorkList();
    // this.getUserList();
    this.getPowerUserList();
    this.getProjectList();
    await this.getProjectTypeList();
    this.getWorkKindList();
    this.getWorkSetByUserId();
    // let param = {
    //   id: 67,
    //   username: 'hhl',
    //   oldPassword: '123456',
    //   newPassword: '1234567'
    // }
    // userApi.updatePassword(param).then(res => {
    //   console.log("密码修改",res)
    // })
    // console.log(JSON.parse(sessionStorage.getItem("userInfo")));
  },
};
</script>
<style lang='scss' scoped>
.reportwork {
  width: 100%;
  height: 100%;
}
/deep/ .el-input__inner {
  color: #999999;
}
.addWork {
  padding-top: 20px;
}
.toolBar {
  display: flex;
}
.content {
  margin-top: 10px;
}
.diaBtn {
  display: flex;
  justify-content: center;
}
.pagination {
  margin-top: 10px;
  width: 100%;
  text-align: center;
}
.reportworkedit {
  background: #ffffff;
  width: 100%;
  overflow: auto;
  padding: 2%;
  margin-top: 1%;
  display: flex;
  flex-direction: column;
  align-items: center;
  .editItem {
    margin-bottom: 2.5%;
    width: 100%;
    span {
      color: #aaaaaa;
      font-size: 14px;
      font-weight: bold;
    }
    .el-input {
      background: #f9f9f9;
      border: none;
      color: #808080;
    }
    .el-select {
      background: #f9f9f9;
      border: none;
      color: #808080;
    }
    div {
      margin-left: 37.5px;
      margin-top: -10px;
    }
  }
  .editButton {
    margin-top: 100px;
  }
}
</style>
<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>